<template>
  <div class="page-mobile-pingtuan">
    <white-header
      :isShowTopNav="true"
      :isShowBack="true"
      :isShowRight="true"
      title="拼团"
    ></white-header>
    <div class="count-down">
        <div class="count-left">精选课程拼团中</div>
        <div class="count-right">
            <span>还剩:</span>
            <span class="block">{{timeObj.days}}</span>
            <span style="margin-right:.1rem">天</span>
            <span class="block">{{timeObj.hours}}</span>
            <span>:</span>
            <span class="block">{{timeObj.minutes}}</span>
            <span>:</span>
            <span class="block">{{timeObj.seconds}}</span>
        </div>
    </div>
    <div class="group-list">
        <group-tuan-cart :detail="item" v-for="(item,index) in groupList" :key="item.id"></group-tuan-cart>
    </div>
  </div>
</template>

<script>
import WhiteHeader from "~/components/mobile/WhiteHeader.vue";
import GroupTuanCart from "~/components/mobile/GroupTuanCart.vue";
import { mapState, mapActions, mapMutations } from "vuex";
import { getCurrentGroupWork } from "~/api/group-booking";
export default {
  props: ["setDisabled", "refreshFun", "setLoading"],
  components: {
    WhiteHeader,
    GroupTuanCart
  },
  data() {
    return {
      that:this,
      groupPages:{
          page:1,
          pageSize:10,
          total:0
      },
      groupList:[],
      timeObj:{
        days:"0",
        hours:"00",
        minutes:"00",
        seconds:"00"
      },//拼团倒计时对象
      timeTimer:null,//拼团倒计时定时器
      maxCount:0,
    };
  },
  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      token(state) {
        return state.token;
      },
      is_ios(state) {
        return state.is_ios;
      },
      is_in_wechat(state) {
        return state.is_in_wechat;
      },
      is_in_minigram(state) {
        return state.is_in_minigram;
      },
      is_loading(state) {
        return state.is_loading;
      },
      is_wechat_ios_limit(state) {
        return state.is_wechat_ios_limit;
      }
    }),
    is_show_price() {
      if (this.is_wechat_ios_limit) {
        return this.is_ios && this.is_in_wechat;
      } else {
        return false;
      }
    },
    
  },
  watch: {},
  filters:{
    
  },
  destroyed() {
    window.removeEventListener("scroll", this.eventListener);
    this.setDisabled(true);
    clearInterval(this.timeTimer);
    this.timeTimer = null;
  },
  deactivated() {
    window.removeEventListener("scroll", this.eventListener);
    this.setDisabled(true);
    clearInterval(this.timeTimer);
    this.timeTimer = null;
  },
  activated() {
    if (process.client) {
      if (!this.token && Object.keys(this.user_info).length == 0) {
        this.$router.replace("/m/login");
      }
      window.addEventListener("scroll", this.eventListener);
    }
    this.initPage()
    this.setDisabled(false);
    this.refreshFun(() => {
      this.initPage()
      this.setLoading(false);
    });
  },
  methods: {
    ...mapActions([]),
    ...mapMutations(["SET_IS_LOADING"]),
    countDown(){
      
      console.log("开启定时器");
      this.timeTimer = setInterval(() => {
        let newTime = this.maxCount - new Date().getTime();  //距离结束时间的毫秒数
        let leftd = Math.floor(newTime/(1000*60*60*24));  //计算天数
        let lefth = Math.floor(newTime/(1000*60*60)%24);  //计算小时数
        let leftm = Math.floor(newTime/(1000*60)%60);  //计算分钟数
        let lefts = Math.floor(newTime/1000%60);  //计算秒数
        let add0 = m => {
          return m < 10 ? "0" + m : m;
        };
        // console.log(leftd + "天" + add0(lefth) + ":" + add0(leftm) + ":" + add0(lefts));  //返回倒计时的字符串
        if(newTime <= 0){
          clearInterval(this.timeTimer);
          this.timeTimer = null;
        }
        this.timeObj = {
          days : leftd,
          hours : add0(lefth),
          minutes : add0(leftm),
          seconds : add0(lefts),
        }
      }, 1000);
    },
    formatDate(date) {
      var date = new Date(date);
      var YY = date.getFullYear() + "-";
      var MM =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      var hh =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      var mm =
        (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
        ":";
      var ss =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return YY + MM + DD + " " + hh + mm + ss;
    },
    async getGroupList(){
      let params = {
        offset: this.groupPages.pageSize * (this.groupPages.page - 1),
        limit: this.groupPages.pageSize,
        sort: "id",
        sortType: "desc",
      };
      let result = await getCurrentGroupWork(params);
      if(result && result.data && result.data.code == 200){
        this.groupList = result.data.data.rows;
        this.groupPages.total = result.data.data.total;
        if(this.groupPages.total > 0){
            this.maxCount = Math.max.apply(Math,this.groupList.map(item => { return item.endTime }));
            this.countDown();
            console.log("最大值:",this.maxCount);
        }
        
      }else{
        this.$toast("获取失败！");
      }
    },
    initPage(){
        clearInterval(this.timeTimer);
        this.timeTimer = null;
        this.groupPages = {
            page: 1,
            pageSize: 10,
            total: 0
        };
        this.getGroupList();
    },
    pullUp() {
      // 滚动条离顶部的距离
      let scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      // 窗口可视区域高度
      let clientHeight =
        document.documentElement.clientHeight || document.body.clientHeight;
      // 滚动区域高度
      let scrollHeight =
        document.documentElement.scrollHeight || document.body.scrollHeight;
      // 滚动条 + 可视区域高度 >= 滚动条高度 ==>  滚动条触底
      if (scrollTop + clientHeight >= scrollHeight - 120) {
        console.log("上拉加载");
        if (
          this.groupPages.total <= this.groupList.length
        ) {
          return;
        }
        if (this.is_loading) {
          return;
        }
        this.groupPages.page++;
        this.getCouponList("pullup");
      }
    },
    eventListener() {
      this.throttle(this.pullUp, 30);
    },
    throttle(fn, delay) {
      let lastTime = 0;
      return !(function() {
        let nowTime = Date.now();
        if (nowTime - lastTime > delay) {
          fn.call(this);
          lastTime = nowTime;
        }
      })();
    }
  },
  created() {
    if (process.client) {
      if (!this.token && Object.keys(this.user_info).length == 0) {
        return this.$router.replace("/m/login");
      }
    }
    this.$nextTick(() => {
      document.body.scrollTop = 0;
      document.documentElement.scrollTop = 0;
    });
    // this.initPage()
    // this.setDisabled(false);
    // this.refreshFun(() => {
    //   this.initPage()
    //   this.setLoading(false);
    // });
  },
  mounted() {
    if (process.client) {
      window.addEventListener("scroll", this.eventListener);
    }
    
  }
};
</script>

<style lang="scss" scoped>
.page-mobile-pingtuan {
  width: 100vw;
  min-height: 100vh;
  background-color: #ffffff;
    background: linear-gradient(135deg, #FF508F 0%, #FF2B57 100%);
    .count-down{
        width: 6.624rem;
        margin: 0 auto;
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 1.344rem;
        .count-left{
            font-size: .3456rem;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            color: #FFFFFF;
        }
        .count-right{
            font-size: .288rem;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            color: #FFFFFF;
            .block{
                display: inline-block;
                min-width: .48rem;
                height: .48rem;
                background: #FFFFFF;
                border-radius: .0768rem;
                text-align: center;
                line-height: .48rem;
                color: var(--theme-color);
            }
        }
    }
    .group-list{
        border:.01rem solid transparent;
    }
}
</style>
<style lang="scss">
.page-mobile-pingtuan {
}
</style>
